package com.peanut.baby.mvp.qadetail;

import android.content.Context;
import android.content.Intent;
import android.content.res.Resources;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.ViewSwitcher;

import androidx.annotation.Nullable;
import androidx.viewpager.widget.ViewPager;

import com.peanut.baby.InitManager;
import com.peanut.baby.R;
import com.peanut.baby.comm.BaseDialog;
import com.peanut.baby.comm.MyViewPagerAdapter;
import com.peanut.baby.db.DBManager;
import com.peanut.baby.http.ApiException;
import com.peanut.baby.model.Ad;
import com.peanut.baby.model.QA;
import com.peanut.baby.model.QAComment;
import com.peanut.baby.model.QaRel;
import com.peanut.baby.model.TaskDBRecord;
import com.peanut.baby.model.UploadConf;
import com.peanut.baby.mvp.BaseMvpActivity;
import com.peanut.baby.mvp.bind.BindMobileActivity;
import com.peanut.baby.mvp.expert.ExpertProfileActivity;
import com.peanut.baby.mvp.login.LoginActivity;
import com.peanut.baby.mvp.profile.ProfileActivity;
import com.peanut.baby.mvp.web.WebViewActivity;
import com.peanut.baby.util.ShareUtil;
import com.peanut.baby.util.TimeUtil;
import com.peanut.baby.widget.VoicePlayView;
import com.peanut.baby.widget.VoiceRecorderView;
import com.peanut.devlibrary.imageloader.ImageLoader;
import com.peanut.devlibrary.media.AudioPlayer;
import com.peanut.devlibrary.picker.PhotoPreviewActivity;
import com.peanut.devlibrary.util.StringUtil;
import com.peanut.devlibrary.widget.TitleLayout;
import com.peanut.devlibrary.widget.pullrecycle.PullRecyclerView;
import com.peanut.devlibrary.widget.pullrecycle.layoutmanager.XLinearLayoutManager;
import com.tencent.mars.xlog.Log;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import cn.sharesdk.sina.weibo.SinaWeibo;
import cn.sharesdk.tencent.qq.QQ;
import cn.sharesdk.wechat.friends.Wechat;
import cn.sharesdk.wechat.moments.WechatMoments;

/**
 * Created by anonymouslystudio on 2017/7/17.
 */

public class QADetailActivity extends BaseMvpActivity implements TitleLayout.OnTitleClickListener,
        View.OnClickListener,
        View.OnTouchListener,
        QADetailContract.View,
        PullRecyclerView.OnRecyclerRefreshListener,
        TextView.OnEditorActionListener ,ViewPager.OnPageChangeListener{
    private static final String TAG = QADetailActivity.class.getSimpleName();
    @BindView(R.id.qa_detail_recycler)
    PullRecyclerView recycler;

    @BindView(R.id.title)
    TitleLayout title;
    @BindView(R.id.qa_input_container)
    LinearLayout qaInputContainer;

    @BindView(R.id.qa_press_to_speak)
    LinearLayout pressToSpeak;
    @BindView(R.id.qa_detail_viewswitcher)
    ViewSwitcher viewswitcher;
    @BindView(R.id.voice_recorder)
    VoiceRecorderView voiceRecorder;
    @BindView(R.id.normal_edit)
    EditText normalEdit;

    private Runnable scrollRunnable;
    private boolean resumed = false;
    private Handler handler = new Handler();

    private TextView comment;
    private TextView answer;

    private TextView askerNick;
    private ImageView askerAvatar;
    private TextView askerDate;

    private TextView qaListenCount;
    private CheckBox qaPrasiedCount;
    private TextView qaCommentCount;
    private TextView qaCategory;
    private TextView qaContent;
    private ImageView qaImage;
    private TextView qaStatus;
    private TextView qaPrice;

    private LinearLayout answerContainer;
    private TextView answerNick;
    private ImageView answerAvatar;
    private TextView answerDate;
    private VoicePlayView answerVoiceView;

    private QADetailPresenter presenter;
    private QACommentListAdapter adapter;
    private List<QAComment> comments;
    private int qaId;
    private int pageNo = 1;
    private int pageSize = 5;


    //rel
    LinearLayout relContainer;
    ViewPager relBViewpager;
    RadioGroup relBRadiogroup;
    FrameLayout relBFrame;
    TextView relPre;
    TextView relNext;
    TextView relPartner;
    LinearLayout relQaContainer;
    protected MyViewPagerAdapter relBAdapter;                      //banner适配器
    protected List<View> relViews;




    private QA qa;


    public static void start(Context ctx, int qaId) {
        ctx.startActivity(new Intent(ctx, QADetailActivity.class).putExtra("id", qaId));
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_qa_detail);
        ButterKnife.bind(this);
        qaId = getIntent().getIntExtra("id", -1);
        if (qaId == -1) {
            Log.d(TAG, "params id not exists, finished");
            finish();
            return;
        }

        initView();
        presenter = new QADetailPresenter(this, this);

        presenter.getQADetail(qaId + "");
        presenter.getCommentList(qaId + "", pageNo, pageSize);
        presenter.getQARel(qaId);
    }

    @Override
    protected void onResume() {
        super.onResume();
        resumed = true;
        handler.postDelayed(scrollRunnable, 3000);

    }


    @Override
    protected void onPause() {
        super.onPause();
        if (answerVoiceView.isPlaying()) {
            answerVoiceView.stopPlay();
        }
        resumed = false;
        handler.removeCallbacks(scrollRunnable);
    }

    @Override
    protected void onDestroy() {
        AudioPlayer.getInstance().onDestory();
        super.onDestroy();

    }

    /**
     *
     */
    private void initView() {
        title.setOnTitleClickedListener(this);
        title.setTitle("问答详情");
        title.setTitleRightTextDrawable("", R.drawable.icon_share);
        title.setTitleRightVisibility(true);

        pressToSpeak.setOnTouchListener(this);
        voiceRecorder.setVoicePath(InitManager.getInstance().getVoiceDir());

        recycler.enableLoadMore(true);
        recycler.enablePullRefresh(true);
        recycler.setOnRecyclerRefreshListener(this);

        View header = LayoutInflater.from(this).inflate(R.layout.layout_qa_detail_header, null);
        comment = header.findViewById(R.id.comment_write);
        comment.setOnClickListener(this);
        answer = header.findViewById(R.id.comment_answer);
        answer.setOnClickListener(this);

        if (InitManager.getInstance().getUser() != null && InitManager.getInstance().getUser().canAnswerQuestion()) {
            answer.setVisibility(View.VISIBLE);
        }

        initHeaderView(header);

        recycler.setLayoutManager(new XLinearLayoutManager(this));
        comments = new ArrayList<>();
        adapter = new QACommentListAdapter(this, comments);
        recycler.setAdapter(adapter);
        recycler.addHeaderView(header);

        if (InitManager.getInstance().getUser() == null
                || !InitManager.getInstance().getUser().canAnswerQuestion()) {
            //for tourist and normal user, hide inputbar with voice record
            qaInputContainer.setVisibility(View.GONE);
        }

        scrollRunnable = new Runnable() {
            @Override
            public void run() {
                if (relBAdapter != null && relBAdapter.getCount() > 0) {
                    int currentIndex = relBViewpager.getCurrentItem();
                    int pos = currentIndex + 1;
                    if (pos > relBAdapter.getCount() - 1) {
                        pos = 0;
                    }

                    relBViewpager.setCurrentItem(pos);
                }
                if (resumed) {
                    handler.postDelayed(scrollRunnable, 3000);
                }
            }
        };

    }

    private void initHeaderView(View header) {
        askerNick = header.findViewById(R.id.qa_asker_nick);
        askerAvatar = header.findViewById(R.id.qa_asker_avatar);
        askerDate = header.findViewById(R.id.qa_asker_date);
        qaImage = header.findViewById(R.id.qa_image);
        qaCategory = header.findViewById(R.id.qa_category);
        qaContent = header.findViewById(R.id.qa_content);
        qaStatus = header.findViewById(R.id.qa_status);
        qaPrice = header.findViewById(R.id.qa_price);
        qaListenCount = header.findViewById(R.id.qa_listen_count);
        qaPrasiedCount = header.findViewById(R.id.qa_prasied_count);
        qaCommentCount = header.findViewById(R.id.qa_comment_count);

        answerContainer = header.findViewById(R.id.qa_answer_container);
        answerNick = header.findViewById(R.id.qa_answer_nick);
        answerAvatar = header.findViewById(R.id.qa_answer_avatar);
        answerDate = header.findViewById(R.id.qa_answer_date);
        answerVoiceView = header.findViewById(R.id.qa_answer_voice_view);

        //rel
        relContainer = header.findViewById(R.id.rel_container);
        relBViewpager = header.findViewById(R.id.rel_banner_viewpager);
        relBRadiogroup = header.findViewById(R.id.rel_banner_radiogroup);
        relBFrame = header.findViewById(R.id.rel_banner_frame);
        relPre = header.findViewById(R.id.rel_pre);
        relNext = header.findViewById(R.id.rel_next);
        relPartner = header.findViewById(R.id.rel_partner);
        relQaContainer = header.findViewById(R.id.rel_qa_container);
        fixRelBannerSize();

        qaImage.setOnClickListener(this);
        answerVoiceView.setOnClickListener(this);
        normalEdit.setOnEditorActionListener(this);
        qaPrasiedCount.setOnClickListener(this);
        askerAvatar.setOnClickListener(this);
        answerAvatar.setOnClickListener(this);
    }

    private void fixRelBannerSize(){
        //
        LinearLayout.LayoutParams params = (LinearLayout.LayoutParams) relBFrame.getLayoutParams();
        params.height = InitManager.getInstance().getScreenWidth() * 3 / 5;
        relBFrame.setLayoutParams(params);
    }



    private void updateView() {
        if (qa == null) {
            return;
        }

        //asker info
        ImageLoader.loadImageView(QADetailActivity.this, qa.creatorAvatar, askerAvatar);
        askerNick.setText(qa.creatorNickname);
        askerDate.setText(TimeUtil.getQAListDisplayTime(qa.createTime));

        qaStatus.setText(qa.getStatusString());
        qaContent.setText(qa.description);
        qaCategory.setText(qa.type);
        qaPrice.setText(qa.getPriceString());
        qaListenCount.setText(qa.listenCount + "");
        qaCommentCount.setText(qa.commentCount + "");
        qaPrasiedCount.setText(qa.praiseCount + "");
        qaPrasiedCount.setChecked(qa.isPraised());

        if (qa.isAnswered()) {
            qaStatus.setTextColor(getResources().getColor(R.color.colorPrimary));
        } else {
            qaStatus.setTextColor(getResources().getColor(R.color.text_dark));
        }


        if (StringUtil.isNullOrEmpty(qa.imageUrl)) {
            qaImage.setVisibility(View.GONE);
        } else {
            ImageLoader.loadImageView(QADetailActivity.this, qa.imageUrl, qaImage);
            qaImage.setVisibility(View.VISIBLE);
        }

        //answer info
        try {
            if (qa.isAnswered()) {
                answer.setVisibility(View.GONE);
                answerContainer.setVisibility(View.VISIBLE);
                ImageLoader.loadImageView(QADetailActivity.this, qa.doctorAvatar, answerAvatar);
                answerNick.setText(qa.doctorNickname);
                answerVoiceView.setDuration(qa.duration);
                answerDate.setText(TimeUtil.getQAListDisplayTime(qa.answerTime));
            } else {
                answerContainer.setVisibility(View.GONE);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onTitleBackClicked() {
        finish();
    }

    @Override
    public void onTitleRightClicked() {
        new BaseDialog().showShareDialog(QADetailActivity.this, new BaseDialog.OnShareItemSelected() {
            @Override
            public void onShareItemSelected(int item) {
                String platName = "";
                if (item == BaseDialog.OnShareItemSelected.TYPE_MOMENT) {
                    platName = WechatMoments.NAME;
                } else if (item == BaseDialog.OnShareItemSelected.TYPE_WEIXIN) {
                    platName = Wechat.NAME;
                } else if (item == BaseDialog.OnShareItemSelected.TYPE_WEIBO) {
                    platName = SinaWeibo.NAME;
                } else if (item == BaseDialog.OnShareItemSelected.TYPE_QQ) {
                    platName = QQ.NAME;
                }
                if (StringUtil.isNullOrEmpty(platName)) {
                    return;
                }
                ShareUtil.getInstance().shareQA(qa, platName, new ShareUtil.IShareCallback() {
                    @Override
                    public void onShareFinished(boolean isSuccess, String platformName, String failReason) {
                        showToast(isSuccess ? "分享成功" : failReason);
                        if (isSuccess && InitManager.getInstance().getUser() != null) {
                            TaskDBRecord record = DBManager.getInstance().getTaskRecord(Integer.parseInt(InitManager.getInstance().getUserId()), com.peanut.devlibrary.util.TimeUtil.getCurrentDate());
                            record.shareQACount++;
                            if (record.shareQACount > 1) {
                                record.shareQACount = 1;
                            } else {
                                presenter.sharePoint(qaId + "");
                            }
                            DBManager.getInstance().updateTaskRecord(record);
                        }
                    }
                });
            }
        });
    }

    @Override
    public void onTitleClicked() {

    }

    @Override
    public void onClick(View v) {
        if (qa == null) {
            return;
        }

        switch (v.getId()) {
            case R.id.comment_write:
                //first check if logged
                if (InitManager.getInstance().getUser() == null) {
                    LoginActivity.startForResult(this);
                    return;
                }
                if (StringUtil.isNullOrEmpty(InitManager.getInstance().getUser().userToken)) {
                    BindMobileActivity.startForResult(this);
                    return;
                }

                if (qaInputContainer.getVisibility() == View.VISIBLE) {
                    qaInputContainer.setVisibility(View.GONE);
                    return;
                }
                qaInputContainer.setVisibility(View.VISIBLE);

                if (viewswitcher.getCurrentView() == pressToSpeak) {
                    viewswitcher.showPrevious();
                }

                break;
            case R.id.comment_answer:
                //first check if logged
                if (InitManager.getInstance().getUser() == null) {
                    LoginActivity.startForResult(this);
                    return;
                }
                if (StringUtil.isNullOrEmpty(InitManager.getInstance().getUser().userToken)) {
                    BindMobileActivity.startForResult(this);
                    return;
                }

                if (qaInputContainer.getVisibility() == View.VISIBLE) {
                    qaInputContainer.setVisibility(View.GONE);
                    return;
                }
                qaInputContainer.setVisibility(View.VISIBLE);

                if (viewswitcher.getCurrentView() != pressToSpeak) {
                    viewswitcher.showNext();
                }

                presenter.checkAudioPermission(QADetailActivity.this);
                break;
            case R.id.qa_image:
                ArrayList<String> urls = new ArrayList<String>();
                urls.add(qa.imageUrl);
                PhotoPreviewActivity.start(this, urls, 0);
                break;
            case R.id.qa_answer_voice_view:
                if (InitManager.getInstance().getUser() == null) {
                    LoginActivity.startForResult(this);
                    return;
                }
                if (StringUtil.isNullOrEmpty(InitManager.getInstance().getUser().userToken)) {
                    BindMobileActivity.startForResult(this);
                    return;
                }

                if (qa.isPay == 0) {
                    if (InitManager.getInstance().getUserId().equals(qa.creatorId + "")
                            || InitManager.getInstance().getUserId().equals(qa.doctorId + "")) {
                        showProgressDialog("请稍候...", false);
                        presenter.getQAAnswerVoice(qaId + "");
                    } else {
                        new BaseDialog().showConfirmCancelAlert(QADetailActivity.this,
                                "播放此回答需要扣除" + qa.listenScore + "粒花生米,是否继续?", "继续", "取消", new View.OnClickListener() {
                                    @Override
                                    public void onClick(View v) {
                                        showProgressDialog("请稍候...", false);
                                        presenter.getQAAnswerVoice(qaId + "");
                                    }
                                }, null);
                    }

                } else {
                    Log.d(TAG, "already pay " + qa.audioUrl);
                    if (StringUtil.isNullOrEmpty(qa.audioUrl)) {
                        showProgressDialog("请稍候...", false);
                        presenter.getQAAnswerVoice(qaId + "");
                    } else {
                        if (answerVoiceView.isPlaying()) {
                            answerVoiceView.stopPlay();
                        } else {
                            answerVoiceView.play(qa.audioUrl);
                        }

                    }

                }


                break;
            case R.id.qa_prasied_count:
                qaPrasiedCount.setText(qa.praiseCount + "");
                qaPrasiedCount.setChecked(qa.isPraised());

                if (InitManager.getInstance().getUser() == null) {
                    LoginActivity.startForResult(this);
                    return;
                }
                if (StringUtil.isNullOrEmpty(InitManager.getInstance().getUser().userToken)) {
                    BindMobileActivity.startForResult(this);
                    return;
                }

                presenter.praiseQA(qaId + "");
                break;
            case R.id.qa_asker_avatar:
                ProfileActivity.start(QADetailActivity.this, qa.creatorId + "");
                break;
            case R.id.qa_answer_avatar:

                if (InitManager.getInstance().getUser() == null) {
                    LoginActivity.startForResult(QADetailActivity.this);
                    return;
                }
                if (StringUtil.isNullOrEmpty(InitManager.getInstance().getUser().userToken)) {
                    BindMobileActivity.startForResult(QADetailActivity.this);
                    return;
                }
                ExpertProfileActivity.start(QADetailActivity.this, qa.doctorId + "");

                break;
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if (qaInputContainer.getVisibility() != View.GONE) {
                qaInputContainer.setVisibility(View.GONE);
                return true;
            }

        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    public boolean onTouch(View v, MotionEvent event) {
        return voiceRecorder.onPressToSpeakBtnTouch(v, event, new VoiceRecorderView.VoiceRecorderCallback() {
            @Override
            public void onVoiceRecordComplete(String voiceFilePath, int voiceTimeLength) {
                onVoiceRecordFinished(voiceFilePath, voiceTimeLength);
            }
        });
    }

    private void onVoiceRecordFinished(String path, int duration) {
        showProgressDialog("请稍候...", false);
        presenter.uploadCommentVoice(path, duration);
    }

    @Override
    public void onAudioUploadFinished(boolean success, String failReason, UploadConf conf) {
        dismissProgressDialog();
        if (success) {
            showProgressDialog("请稍候...", false);
            presenter.sendAnswer(conf.getResultFullUrl(), conf.duration, qaId + "");
        } else {
            showToast(failReason);
        }

    }

    @Override
    public void onRequestFailed(String code, String reason) {
        dismissProgressDialog();
        if (!ApiException.isApiException(code)) {
            showToast(reason);
        }
    }

    @Override
    public void onSendCommentFinished(boolean success, String failReason, QAComment resultObj) {
        dismissProgressDialog();
        if (success) {
            qaInputContainer.setVisibility(View.GONE);
            qa.commentCount++;
            qaCommentCount.setText(qa.commentCount + "");

            normalEdit.setText("");
            recycler.onRefresh();
            hideSoftKeyboard();

        }
    }

    @Override
    public void onGetCommentFinished(boolean success, String failReason, List<QAComment> resultObj) {
        recycler.stopLoadMore();
        recycler.stopRefresh();
        if (success) {
            if (resultObj != null && !resultObj.isEmpty()) {
                if (pageNo == 1) {
                    comments.clear();
                }
                comments.addAll(resultObj);
            }
            adapter.notifyDataSetChanged();
            recycler.enableLoadMore(resultObj.size() >= pageSize);
        } else {
            recycler.enableLoadMore(false);
        }
    }

    @Override
    public void onGetQADetailFinished(boolean success, String failReason, QA resultObj) {
        dismissProgressDialog();
        if (success) {
            this.qa = resultObj;
            updateView();

        } else {
            showToast("获取问答详情失败 " + failReason);
            finish();
        }
    }

    @Override
    public void onSendAnswerFinished(boolean success, String failReason, QA resultObj) {
        dismissProgressDialog();
        qaInputContainer.setVisibility(View.GONE);
        if (success) {
            qa = resultObj;
            updateView();
        }
    }

    @Override
    public void onAudioPermissionGranted() {
        //do nothing...
    }

    @Override
    public void onAudioPermissionDenied() {
        new BaseDialog().showConfirmAlert(QADetailActivity.this, "您无法使用录音功能，请到系统设置中打开录音和文件权限后使用", "确定", new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                qaInputContainer.setVisibility(View.GONE);
            }
        });
    }

    @Override
    public void onAnswerVoiceGet(String _url) {
        Log.d(TAG, "onAnswerVoiceGet " + _url);
        dismissProgressDialog();
        //answerVoiceView.play(url);
        qa.audioUrl = _url;
        qa.isPay = 1;
        answerVoiceView.play(qa.audioUrl);
    }

    @Override
    public void onPraiseSuccess(QA praised) {
        this.qa = praised;
        updateView();
    }



    @Override
    public void onSharePointSuccess(String tips) {
        showToast(tips);
    }

    @Override
    public void onQARelGet(boolean success, QaRel rel, String failReason) {
        if(!success || rel == null || rel.hasEmpty()){
            relContainer.setVisibility(View.GONE);
        }else{
            relContainer.setVisibility(View.VISIBLE);
            relPre.setOnClickListener(null);
            relNext.setOnClickListener(null);
            relPartner.setOnClickListener(null);

            initRelBanners(rel.goodsList);
            if(rel.preUrl != null && rel.preUrl.id > 0){
                relPre.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        QADetailActivity.start(QADetailActivity.this,rel.preUrl.id);
                    }
                });
            }
            if(rel.nextUrl != null && rel.nextUrl.id > 0){
                relNext.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        QADetailActivity.start(QADetailActivity.this,rel.nextUrl.id);
                    }
                });
            }
            if(!StringUtil.isNullOrEmpty(rel.hhrUrl)){
                relPartner.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        WebViewActivity.start(QADetailActivity.this,rel.hhrUrl,"花生好孕优选梦想合伙人","");
                    }
                });
            }
            if(rel.qaRel != null && !rel.qaRel.isEmpty()){
                initRelQas(rel.qaRel);
            }
        }
    }
    //隐藏推荐的banner
    private void fakeHideRelBanner(){
        //
        LinearLayout.LayoutParams params = (LinearLayout.LayoutParams) relBFrame.getLayoutParams();
        params.height = 1;
        relBFrame.setLayoutParams(params);
    }
    //
    private void initRelQas(List<QA> qas){
        if(qas == null || qas.isEmpty()){
            return;
        }
        relQaContainer.removeAllViews();
        int len = qas.size();
        for(int i=0;i<len;i++){
            final QA qa = qas.get(i);
            final View relView = getLayoutInflater().inflate(R.layout.layout_rel_item, null);
            final TextView relText = relView.findViewById(R.id.rel_text);
            relText.setText(qa.description);
            relText.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    QADetailActivity.start(QADetailActivity.this,qa.id);
                }
            });
            relQaContainer.addView(relView);
        }
    }
    //显示推荐的 banner
    private void initRelBanners(final List<Ad> objs) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                if (objs == null || objs.isEmpty()) {
                    fakeHideRelBanner();
                    return;
                }
                fixRelBannerSize();
                if (relViews == null) {
                    relViews = new ArrayList<View>();
                }
                relViews.clear();
                relBRadiogroup.removeAllViews();
                int size = objs.size();
                int rightMargin = getResources().getDimensionPixelSize(R.dimen.ad_radio_size);
                for (int i = 0; i < size; i++) {
                    final Ad ad = objs.get(i);
                    final View adView = getLayoutInflater().inflate(R.layout.layout_ad, null);
                    final ImageView img = adView.findViewById(R.id.ad_image);

                    ImageLoader.loadImageView(QADetailActivity.this, ad.imgUrl, img);


                    relViews.add(adView);

                    adView.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            WebViewActivity.start(QADetailActivity.this, ad.htmlUrl, ad.name,ad.imgUrl);
                        }
                    });

                    RadioButton radioButton = new RadioButton(QADetailActivity.this);
                    radioButton.setButtonDrawable(new ColorDrawable(Color.TRANSPARENT));
                    try {
                        radioButton.setBackgroundDrawable(QADetailActivity.this.getResources().getDrawable(R.drawable.selector_ad_radiobutton));
                    } catch (Resources.NotFoundException e) {
                        e.printStackTrace();
                    }
                    RadioGroup.LayoutParams params = new RadioGroup.LayoutParams(rightMargin, rightMargin);
                    if (i != (size - 1)) {
                        params.rightMargin = rightMargin;
                    }
                    relBRadiogroup.addView(radioButton, params);


                }
                ((RadioButton) relBRadiogroup.getChildAt(0)).setChecked(true);
                relBAdapter = new MyViewPagerAdapter(relViews);
                relBViewpager.setAdapter(relBAdapter);
                relBViewpager.setOnPageChangeListener(QADetailActivity.this);

            }
        });

    }


    @Override
    public void onPullRefresh() {
        pageNo = 1;
        presenter.getCommentList(qaId + "", pageNo, pageSize);
    }

    @Override
    public void onLoadMore() {
        pageNo++;
        presenter.getCommentList(qaId + "", pageNo, pageSize);
    }

    @Override
    public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
        Log.d(TAG, "actionId: " + actionId);
        if (actionId == EditorInfo.IME_ACTION_SEND) {
            sendComment();
            return true;
        }
        return false;
    }

    private void sendComment() {
        String text = normalEdit.getText().toString().trim();
        if (TextUtils.isEmpty(text)) {
            showToast("请输入要发送的内容");
            return;
        }
        showProgressDialog("请稍候...", false);
        presenter.sendComment(text, qaId + "");
    }

    @Override
    public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

    }

    @Override
    public void onPageSelected(int position) {
        ((RadioButton) relBRadiogroup.getChildAt(position)).setChecked(true);
    }

    @Override
    public void onPageScrollStateChanged(int state) {

    }
}
